package com.os.opencv.java.chapter9;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class ContourArea {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("/Users/matt/Pictures/dog.jpg", Imgcodecs.IMREAD_GRAYSCALE);
        HighGui.imshow("src", src);
        HighGui.waitKey(0);

        Mat binary = new Mat();
        Imgproc.threshold(src, binary, 90, 255, Imgproc.THRESH_BINARY);

        HighGui.imshow("binary", binary);
        HighGui.waitKey(0);

        //根据而知图检测轮廓
        List<MatOfPoint> contour = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(binary, contour, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);

        //在控制台显示各个轮廓的面积
        for(int i=0; i<contour.size(); i++){
            double d = Imgproc.contourArea(contour.get(i));
            System.out.println(i + ": " + d);
        }
        System.exit(0);

    }
}
